import tkinter as tk
from logitics import *
from utils import img_resize,DynamicImage
from PIL import Image,ImageTk
from pygame import mixer
from pathlib import Path
from time import time

mixer.init()
root_path=Path(__file__).parent.parent
mixer.music.load(root_path.joinpath(Path(r'sounds\BGM16.mid')))
mixer.music.play(loops=-1)
#BGM03结束时使用，BGM16游戏内使用

WIDTH = HEIGHT = 700
SIZE = 6    #必须为偶数
UNIT = WIDTH // SIZE
level={'简单':4,'普通':10,'困难':16,'地狱':20}

main_win=tk.Tk()
main_win.geometry(str(WIDTH) + 'x' + str(HEIGHT))
main_win.title('熊猫连连看')

def level_choose(text):
    mixer.music.pause()
    begin_time = time()

    SIZE=level[text]
    simple_button.destroy()
    normal_button.destroy()
    hard_button.destroy()
    hell_button.destroy()
    #进入游戏界面
    canvas = tk.Canvas(main_win, width = WIDTH, height = HEIGHT, bg = 'white')
    canvas.pack()
    random_mat=init_randmat(SIZE)
    UNIT=WIDTH//SIZE
    imgs=img_resize(SIZE,UNIT)
    img_list=[]
    for i in range(1, SIZE + 1):
        for j in range(1, SIZE + 1):
            img = imgs[random_mat[i, j]]
            canvas.create_image((j - 1) * UNIT + UNIT // 2, (i - 1) * UNIT + UNIT // 2, image = img)
            # 保留对ImageTk对象的引用，以防止它被垃圾回收
            img_list.append(img)
    canvas.images = img_list

    click_first = False
    firstX, firstY = None, None

    #定义鼠标左键
    def left_button(event):
        #音效加载
        mixer.music.load(root_path.joinpath(Path('sounds\hit1.wav')))
        mixer.music.play()

        nonlocal click_first, firstX, firstY
        click_first = True if not click_first else False
        print(click_first)
        x, y = event.y // UNIT, event.x // UNIT
        if click_first:
            firstX, firstY = x, y
        print(x, y)
        canvas.create_rectangle(y * UNIT, x * UNIT, (y + 1) * UNIT, (x + 1) * UNIT, outline = 'yellow', width = 1)
        if not click_first:
            if if_connected((firstX + 1, firstY + 1), (x + 1, y + 1),random_mat,SIZE):
                #音效加载
                mixer.music.load(root_path.joinpath(Path('sounds\done.wav')))
                mixer.music.play()

                canvas.create_rectangle(firstY * UNIT, firstX * UNIT, (firstY + 1) * UNIT, (firstX + 1) * UNIT,
                                        fill = 'white')
                canvas.create_rectangle(y * UNIT, x * UNIT, (y + 1) * UNIT, (x + 1) * UNIT, fill = 'white')
                canvas.create_rectangle(firstY * UNIT, firstX * UNIT, (firstY + 1) * UNIT, (firstX + 1) * UNIT,
                                        outline = 'black', width = 1)
                canvas.create_rectangle(y * UNIT, x * UNIT, (y + 1) * UNIT, (x + 1) * UNIT, outline = 'black',
                                        width = 1)
                random_mat[firstX + 1, firstY + 1] = random_mat[x + 1, y + 1] = -1
            else:
                #音效加载
                mixer.music.load(root_path.joinpath(Path('sounds\die.wav')))
                mixer.music.play()

                canvas.create_rectangle(firstY * UNIT, firstX * UNIT, (firstY + 1) * UNIT, (firstX + 1) * UNIT,
                                        outline = 'black', width = 1)
                canvas.create_rectangle(y * UNIT, x * UNIT, (y + 1) * UNIT, (x + 1) * UNIT, outline = 'black',
                                        width = 1)
            print(random_mat)
        if (random_mat[::]==-1).all():
            # 音效加载
            mixer.music.load(root_path.joinpath(Path('sounds\BGM03.mid')))
            mixer.music.play()

            end_time=time()
            cost=end_time-begin_time
            print('cost:',cost)

            filename_dic={4:'easy',10:'normal',16:'difficult',20:'hell'}
            filename=filename_dic[SIZE]

            with open(root_path.joinpath('record/'+filename+'.txt'), 'a+') as f:
                f.write(str(cost)+'\n')
                f.seek(0)
                l=[float(i[:-1]) for i in f.readlines()]
                best_record=min(l)
                print('历史最佳成绩为：{:.2f}s'.format(best_record))

            # canvas.destroy()
            file_path=root_path.joinpath('pictures/finish.png')
            image = Image.open(file_path)
            image = image.resize((WIDTH,WIDTH))
            photo = ImageTk.PhotoImage(image)
            image_item = canvas.create_image(WIDTH, 0, anchor = "nw", image = photo)
            canvas.image=photo
            text_item1 = canvas.create_text(WIDTH + 200, 100, anchor = "nw", text = "你的成绩：{:.2f}s".format(cost),
                                           font = ("Arial", 20), fill = "red")
            text_item2 = canvas.create_text(WIDTH + 200, 200, anchor = "nw", text = "历史最佳：{:.2f}s".format(best_record),
                                           font = ("Arial", 20), fill = "red")
            #动画加载
            def animate_image():
                canvas.move(image_item, -2, 0)
                canvas.move(text_item1, -2, 0)
                canvas.move(text_item2, -2, 0)
                canvas.update()
                if canvas.coords(image_item)[0] > 0:
                    main_win.after(10, animate_image)
            # Call function to animate image
            main_win.after(1000, animate_image)
            print('Victory!Game over.')
            main_win.unbind('<Button-1>')

            # main_win.destroy()
    main_win.bind('<Button-1>', left_button)


simple_button = tk.Button(main_win,text="简单",font=('Arial',20), command=lambda: level_choose("简单"))
normal_button = tk.Button(main_win,text="普通",font=('Arial',20), command=lambda: level_choose("普通"))
hard_button = tk.Button(main_win,text="困难",font=('Arial',20), command=lambda: level_choose("困难"))
hell_button = tk.Button(main_win,text="地狱",font=('Arial',20), command=lambda: level_choose("地狱"))

w,h=500,100
simple_button.place(x=100,y=60,width=w,height=h)
normal_button.place(x=100,y=220,width=w,height=h)
hard_button.place(x=100,y=380,width=w,height=h)
hell_button.place(x=100,y=540,width=w,height=h)

main_win.mainloop()